<?php 


function base64url_decode($base64url) {
	$base64 = strtr($base64url, '-_', '+/');
	$plainText = base64_decode($base64);
	return ($plainText);
}
function base64url_encode($plainText) {
	$base64 = base64_encode($plainText);
	$base64url = strtr($base64, '+/', '-_');
	return ($base64url);   
}


function encode_url(&$value, $key) {
	$value = stripcslashes(rawurlencode($value));
}
function rp($p) {
    $p=explode('/', $p);
    $o=array();
    for ($i=0; $i<sizeof($p); $i++) {
        if (''==$p[$i] || '.'==$p[$i]) continue;
        if ('..'==$p[$i] && $i>0 && '..'!=$o[sizeof($o)-1]) {
            array_pop($o);
            continue;
        }
        array_push($o, $p[$i]);
    }
    return implode('/', $o);
}







if (isset($_GET['path'])) { //processing a folder
	$audioTypes = array('mp3','au','wav','aiff','m4a');
	$remdir = base64url_decode($_GET['path']);

	$dir_handle = @opendir($remdir) or die("Unable to open $remdir");
	while ($file = readdir($dir_handle)) {
		if (!is_dir($file)) {
			$items = explode('.',$file);
			$filetype = $items[count($items)-1];
			$filetype = strtolower($filetype);
			if (in_array($filetype,$audioTypes)) $files[] = $file;	
		}
	}
	natcasesort($files);
	closedir($dir_handle);

	$thisdir = $_SERVER["SCRIPT_NAME"];

	$items = explode('/',$thisdir);
	$items[count($items)-1] = '';
	$thisdir = implode('/',$items);

	$items = explode('/',$remdir);

	header('Content-type: audio/x-Mpegurl');
	header('Content-Disposition: attachment; filename="'.urlencode($items[count($items)-1]).'.m3u"');

	foreach ($files as $stritem) {
		$outdir = "$remdir/$stritem";
		$getdir = $outdir;
	
		$items = explode('/',$outdir);
		array_walk($items,'encode_url');
		$outdir = implode('/',$items);
	
		//$outdir = urlencode($outdir);
	
		print 'http://'.$_SERVER["HTTP_HOST"].'/'.rp("$thisdir$outdir")."\n";
	}
}





if (isset($_POST['filelist'])) {//processing a list of files via POST
	
	$filePaths = explode('!',$_POST['filelist']);

	header('Content-type: audio/x-Mpegurl');
	header('Content-Disposition: attachment; filename="Musiker_'.date('ymd.Hi').'.m3u"');
	
	foreach ($filePaths as $stritem) {
		$fileLocation = base64url_decode($stritem);
		
		$items = explode('/',$fileLocation);
		array_walk($items,'encode_url');
		$fileLocation = implode('/',$items);
		
		print 'http://'.$_SERVER["HTTP_HOST"].dirname($_SERVER['REQUEST_URI']).'/'.rp("$fileLocation")."\n";
	}
}

?>
